//JdbcUtils.java
package com.ylaihui.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcUtils {
    private static DruidDataSource dataSource;
    private static ThreadLocal<Connection> connectionThreadLocal = new ThreadLocal<>();

    // 静态代码块，初始化连接池， 类加载的时候就能初始化连接池

    static {
        try {
            InputStream resourceAsStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties properties = new Properties();
            properties.load(resourceAsStream);
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static Connection getConnection() {
        Connection conn = connectionThreadLocal.get();
        if (conn == null) {
            try {
                conn = dataSource.getConnection();
                // 将数据库的连接放入到 线程特定数据中
                connectionThreadLocal.set(conn);
                // 获取连接后，事务开始， 关闭自动提交
                conn.setAutoCommit(false);

            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return conn;
    }

    //public static void colseConnection(Connection conn) {
    //    if (conn != null) {
    //        try {
    //            conn.close();
    //        } catch (SQLException throwables) {
    //            throwables.printStackTrace();
    //        }
    //    }
    //}

    public static void commitAndCloseConn(){
        Connection connection = connectionThreadLocal.get();
        if (connection != null) {
            try {
                // 提交事务，关闭数据库连接
                connection.commit();
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        //Tomcat服务器底层使用了线程池技术， 需要将线程数据删除
        connectionThreadLocal.remove();
    }

    /**
     *
     * @param conn
     */
    public static void rollbackAndCloseConn(){
        Connection connection = connectionThreadLocal.get();
        if (connection != null) {
            try {
                // 回滚事务，关闭数据库连接
                connection.rollback();
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        //Tomcat服务器底层使用了线程池技术， 需要将线程数据删除
        connectionThreadLocal.remove();
    }

}


